// RWScore.cpp
#include "RWScore.h"
#include <QDebug>

QMutex scoreMutex; // 定义全局互斥锁

int readScore() {
    QMutexLocker locker(&scoreMutex); // 自动加锁

    QString scorePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/scores.txt";
    QFile file(scorePath);

    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        int maxScore = 0;
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            bool ok;
            int temp = line.toInt(&ok);
            if (ok && temp > maxScore) maxScore = temp;
        }
        return maxScore;
    } else {
        qWarning() << "读取分数失败:" << file.errorString();
        return 0;
    }
}

void writeScore(int score) {
    QMutexLocker locker(&scoreMutex); // 自动加锁

    QString scorePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/scores.txt";
    QFile file(scorePath);

    // 确保目录存在
    QDir().mkpath(QFileInfo(scorePath).path());

    if (file.open(QIODevice::Append | QIODevice::Text)) {
        QTextStream out(&file);
        out << score << "\n";
    } else {
        qWarning() << "写入分数失败:" << file.errorString();
    }
}
